/**
 * http请求
 * @param url
 * @param type
 * @param data
 */
function ajax({ url, type = 'post', data = {} }) {
    const promise = new Promise(function (resolve, reject) {
        const handle = function () {
            if (this.readyState != 4) {
                return;
            }
            if (this.status == 200) {
                resolve(this.response); //请求成功,抛出接收到的信息
            } else {
                reject(this.response); //请求失败,打印出请求错误信息
            }
        };
        const xml = new XMLHttpRequest(); //创建xml对象,用于发送请求
        xml.open(type, url); //设置发送请求的类型,和地址
        xml.responseType = 'json'; //设置请求数据的类型
        xml.onreadystatechange = handle;
        if (type == 'get') {
            xml.send();
        } else {
            xml.setRequestHeader('Content-Type', 'application/json'); //设置post请求头
            xml.send(JSON.stringify(data)); //data序列化
        }
    });
    return promise;
}
function get(url){
    return ajax({url});
}
function post(url, data){
    return ajax({url, type:'post', data});
}
function put(url, data){
    return ajax({url, type:'put', data});
}
const httpUtils = {
    get,post,put,ajax
}
export {
    httpUtils
}
